import errorManager from '@ohos.app.ability.errorManager';
import { UnhandledExceptionHandler, IExceptionCallback } from './ExceptionBaseData';

/**
 * 需要再destroy的时候退出.
 * UIAbility开启式注册
 * destroy时关闭.
 */
export class ExceptionManager {
  static crash() {
    let r1 = 1/0;
    let r2:string = null;
    let c = r2.charAt(0);
    return c;

  }
  private static registerId:number;
  static registerExceptionHandler(handler:UnhandledExceptionHandler) {
    let callback = {
      onUnhandledException:handler
    }
    this.registerId = errorManager.on("error", callback);
  }

  /**
   * 本来抛出异常,会闪退,这里进行处理后,就不会闪退.
   * @param observer
   */
  static registerExceptionObserver(observer:errorManager.ErrorObserver) {
    let registerId =  errorManager.on("error", observer);
    this.registerId = registerId;
  }

  static unregisterExceptionCallback() {
    if(this.registerId) {
      errorManager.off("error", this.registerId, (result) => {
        console.log("[Demo] result " + result.code + ";" + result.message)
      });
    }
  }
  // let registerId = -1;
  // let callback = {
  //   onUnhandledException: function (errMsg) {
  //     console.log(errMsg);
  //   }
  // }

}